package com.grm.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grm.common.Result;
import com.grm.sys.entity.SysMenu;
import com.grm.sys.entity.SysRole;
import com.grm.sys.entity.SysUser;
import com.grm.sys.service.mapper.SysMenuMapper;
import com.grm.sys.service.mapper.SysRoleMapper;
import com.grm.sys.service.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统用户服务impl
 *
 * @author gaorimao
 * @date 2022/02/07
 */
@Slf4j
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Value("${image.save.os}")
    private String imageSaveOs;

    public List<Map<String, String>> queryUserOptions() {
        return sysUserMapper.queryUserOptions();
    }

    /**
     * 获取用户权限信息(ROLE_admin,ROLE_normal,sys:user:list,sys:role:list)
     *
     * @param userId 用户id
     * @return {@link String}
     */
    public String getUserAuthorityInfo(Long userId) {
        String authority;
        // 1.获取角色代码
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        String queryRoleIdsSql = "select role_id from sys_user_role where user_id = " + userId;
        sysRoleQueryWrapper.inSql("id", queryRoleIdsSql);
        List<SysRole> roles = sysRoleMapper.selectList(sysRoleQueryWrapper);
        String roleCodes = "";
        if (roles.size() > 0) {
            // 查询角色代码
            roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
        }
        authority = roleCodes.concat(",");
        // 2.获取权限代码
        // 2.1 如果角色有admin，默认所有菜单权限
        String menuPerms = "";
        if (roles.size() > 0) {
            List<SysRole> adminRoles = roles.stream().filter(role -> "admin".equals(role.getCode())).collect(Collectors.toList());
            if (adminRoles.size() > 0) {
                List<SysMenu> menus = sysMenuMapper.selectList(null);
                // 查询菜单权限
                menuPerms = menus.stream().map(SysMenu::getPerms).collect(Collectors.joining(","));
            } else {
                menuPerms = getPermsAuthorityByUserId(userId);
            }
        }
        authority = authority.concat(menuPerms);
        return authority;
    }

    /**
     * 通过userId查询所有相关的menuIds
     *
     * @param userId 用户id
     * @return {@link String}
     */
    private String getPermsAuthorityByUserId(Long userId) {
        List<Long> menuIds = sysMenuMapper.queryMenuIdsByUserId(userId);
        String menuPerms = "";
        if (menuIds.size() > 0) {
            List<SysMenu> menus = sysMenuMapper.selectBatchIds(menuIds);
            // 查询菜单权限
            menuPerms = menus.stream().map(SysMenu::getPerms).collect(Collectors.joining(","));
        }
        return menuPerms;
    }

    public void updatePasswordByUsername(String username, String password) {
        sysUserMapper.updatePasswordByUsername(username, password);
    }

    public Result queryPersonalInfo(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        // 不能返回密码
        sysUser.setPassword(null);
        return Result.success("查询个人信息成功！", sysUser);
    }
}
